/** 分页获取订单列表
 * @description 
 * @author unhejing (成都-敬宇杰)
 * @date 2020-02-23 上午11:07:11
 */
'use strict';
const db = uniCloud.database()
const statusEnum = ['待付款','已取消','到付','已支付','已完成']
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event:' + event)
	event.user_id = "1"
	// event.status = 1;
	// event.searchKey = "HTZ2019091010003"
	if (event.user_id == '' || !event.user_id) {
		return {
			success: false,
			code: -1,
			msg: '参数错误，缺少用户id'
		}
	}
	if (!event.page) {
		event.page = 1;
	}
	if (!event.pageSize) {
		event.pageSize = 10;
	}
	console.log('event.page:' + event.page + " event.pageSize:" + event.pageSize + " event.order_code:" + event.order_code)
	// 设置请求参数
	const {
		order_code, //订单搜索关键词
		page,
		pageSize
	} = event
	const collection = db.collection('order') // 获取表'order'的集合对象
	let querySql = {user_id:event.user_id};
	if (!!order_code) {
		querySql.order_code = event.order_code;
	}
	if(!!event.status){
		const dbCmd = db.command;
		let arrStatus;
		if(event.status = 0){
			arrStatus = [0]
		}
		if(event.status = 1){
			arrStatus = [2,3]
		}
		if(arrStatus.length > 0){
			querySql.status = dbCmd.in(arrStatus);
		}
	}
	console.log("查询条件："+JSON.stringify(querySql))
	let res;
	res = await collection.where(querySql).orderBy("create_time", "desc").skip((page - 1) * pageSize).limit(pageSize).get();
	console.log("订单响应数据:" + JSON.stringify(res))
	// res.data.forEach(o=>{
	// 	collection.doc(o._id).set({
	// 		pay_type:0
	// 	});
	// })
	if (!res.data || res.data.length === 0) {
		return {
			success: false,
			code: -1,
			msg: '暂无数据'
		}
	}
	// 获取订单商品
	console.log("***********************华丽的分割线（获取订单商品）***********************")
	// 获取订单code集合
	let orderCodes = new Array();
	let orderList = res.data;
	orderList.map(o => orderCodes.push(o.order_code))
	console.log("订单编码集合：" + JSON.stringify(orderCodes));
	// 查询订单商品行项目
	const dbCmd = db.command;
	let orderProductList = await db.collection('order_product').where({
		order_code: dbCmd.in(orderCodes)
	}).get();
	console.log("订单商品查询结果：" + JSON.stringify(orderProductList))
	// 组装商品到订单
	let orderProductMap = new Map();
	orderProductList.data.forEach(o => {
		let productList = Array.isArray(orderProductMap.get(o.order_code)) ? orderProductMap.get(o.order_code) : new Array();
		productList.push(o)
		orderProductMap.set(o.order_code, productList)
	})
	// 组装数据
	orderList.map(o => {
		o.statusDesc = statusEnum[o.status];
		o.pay_type = o.pay_type == 0 ? '现金支付' : '微信支付'
		if (Array.isArray(orderProductMap.get(o.order_code))) {
			o.productItemList = orderProductMap.get(o.order_code);
		} else {
			o.productItemList = new Array();
		}
	})
	if (res.id || res.affectedDocs >= 1) {
		return {
			success: true,
			code: 0,
			msg: '成功',
			data: orderList
		}
	}
	return {
		success: false,
		code: -1,
		msg: '服务器内部错误'
	}

};



